/*
1、共享内存练习一
	实现reader和writer两个进程通过共享内存交换数据。
	writer从标准输入读入字符串写入共享内存，reader把共享内存里的字符串打印到标准输出。
	reader和writer通过信号实现同步
*/


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>


pid_t writer,reader;

void writer_handler(int signum)
{
	return;
}

void reader_handler(int signum)
{
	return;
}

int main()
{
	char *buff;
	int shmid;

	reader = getpid();
	
	shmid = shmget(34567, 2046, IPC_CREAT|0666);
	if(shmid != -1)
	{
		buff = (char *)shmat(shmid, NULL, 0);
		if(buff == (void *)-1)
			perror("shmat failed");
	}
	else
		perror("shmget failed");
	
	writer = fork();
	if(writer < 0)
		exit(1);
	
	if(writer == 0)
	{
		writer = getpid();
		signal(SIGUSR1, writer_handler);
		while(1)
		{
			printf("write to shm: \n");
			fgets(buff, 64, stdin);
			kill(reader, SIGUSR1);
			if(strcmp(buff, "quit\n") == 0) break;
			pause();
		}

		shmdt(buff);
		shmctl(shmid, IPC_RMID, NULL);
		return 0;
	}
	else
	{
		signal(SIGUSR1, reader_handler);
		while(1)
		{
			pause();
			if(strcmp(buff, "quit\n") == 0) exit(0);
			printf("read from shm : %s\n", buff);
			kill(writer, SIGUSR1);
		}
		
		return 0;
	}

}
